package MapReduce.reduceJoin;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;

public class reduceJoinReducer extends Reducer<Text,TableBean,TableBean, NullWritable> {
    @Override
    protected void reduce(Text key, Iterable<TableBean> values, Reducer<Text, TableBean, TableBean, NullWritable>.Context context) throws IOException, InterruptedException {

        // 准备初始化集合
        ArrayList<TableBean> orderBeans = new ArrayList<>();
        TableBean pdBeans = new TableBean();

        // 循环遍历
        for (TableBean value : values) {
            if("order".equals(value.getFlag())){ // 处理order表
                /**
                 * 此处设置临时tableBean对象原因是：
                 * 若直接遍历用 orderBeans.add(tmptableBean);处理
                 * 每一次只会将tableBeans对象的引用添加进去，
                 * 所以处理完只会保留最后一个tableBean对象
                 */
                TableBean tmptableBean = new TableBean();
                try {

                    // 赋值内容--而非仅复制地址引用
                    BeanUtils.copyProperties(tmptableBean,value);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    throw new RuntimeException(e);
                }

                // 将一个一个的tableBean对象加到List中去
                orderBeans.add(tmptableBean);
            }else { // 处理pd表
                try {
                    BeanUtils.copyProperties(pdBeans,value);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        // 循环遍历orderBeans 赋值pdname
        for (TableBean orderBean : orderBeans) {
            orderBean.setPname(pdBeans.getPname());

            // 写出
            context.write(orderBean,NullWritable.get());
        }
    }
}
